﻿using System;
using System.Reflection;
using System.Runtime.Loader;

namespace ConAppCore.Test
{
    internal class TestPlugin
    {
        public static void Test()
        {
            //    string binPath = sb.ToString();
            //    AppDomain.CurrentDomain.SetData("PRIVATE_BINPATH", binPath);
            //    AppDomain.CurrentDomain.SetData("BINPATH_PROBE_ONLY", binPath);

            var loadContext = new DBPluginLoadContext(@"D:\Projects\UtilZ\UtilZ.DotnetDBEx\Test\ConAppCore\bin\Debug\net8.0\DBPlugins\SqlServer\Debug\net8.0");
            var assemblyName = AssemblyName.GetAssemblyName(@"D:\Projects\UtilZ\UtilZ.DotnetDBEx\Test\ConAppCore\bin\Debug\net8.0\DBPlugins\SqlServer\Debug\net8.0\Microsoft.EntityFrameworkCore.dll");
            Assembly assembly = loadContext.LoadFromAssemblyName(assemblyName);
        }

    }


    internal class DBPluginLoadContext : AssemblyLoadContext
    {
        private readonly string _pluginPath;
        private readonly AssemblyDependencyResolver _resolver;
        public DBPluginLoadContext(string pluginPath)
        {
            this._pluginPath = pluginPath;
            this._resolver = new AssemblyDependencyResolver(pluginPath);
        }

        protected override Assembly Load(AssemblyName assemblyName)
        {
            //string assemblyPath = PathEx.Combine(PathType.Local, this._pluginPath, $"{assemblyName.Name}.dll");
            string assemblyPath = this._resolver.ResolveAssemblyToPath(assemblyName);
            if (!string.IsNullOrWhiteSpace(assemblyPath))
            {
                return LoadFromAssemblyPath(assemblyPath);
            }

            return null;
        }
        protected override nint LoadUnmanagedDll(string unmanagedDllName)
        {
            string libraryPath = this._resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
            if (!string.IsNullOrWhiteSpace(libraryPath))
            {
                return LoadUnmanagedDllFromPath(libraryPath);
            }

            return IntPtr.Zero;
        }

    }
}
